<?php
class ProjectSteps extends CFormModel {

	public $topics;
	public $roots;
	
	public function __construct($project) {
		// 1. on récupère tous les topics déjà créé
		$tmp = $project->topics;
		$topics = array();
		
		if ($tmp != null){
		foreach ($tmp as $topic) {
			$topics[$topic->key] = $topic;
		}
		}
		
		// 2. on prend tous les items et on ajoute ceux qui n'existe pas.
		$tmp = $project->route->steps;
		while (count($tmp) > 0) {
			$item = array_shift($tmp);
			
			if (!array_key_exists($item->key, $topics)) {
				$topic = new ProjectTopic();
				$topic->label = $item->label;
				$topic->description = $item->description;
				$topic->key = $item->key;
				$topic->parent_key = $item->parent_key;
				$topic->start_date = DateUtils::add(DateUtils::today(), DateUtils::DAY, $item->weeks_before*7);
				$topic->end_date = DateUtils::add(DateUtils::today(), DateUtils::DAY, ($item->weeks_before+$item->weeks_number)*7);
				$topic->project_id = $project->id;
				if ($item instanceof Topic) {
					$topic->topic_id = $item->id;
					$topic->item_type = ProjectTopic::TOPIC; 
				} else {
					$topic->step_id = $item->id;
					$topic->item_type = ProjectTopic::STEP; 
				}
				$topic->adviser_validation = $topic->owner_validation = $topic->objective = ProjectTopic::NO;
				$topics[$topic->key] = $topic;
			}
		
			if ($item->topics != null) {
				foreach ($item->topics as $topic) {
					 array_unshift($tmp, $topic);
				}
			}
		}
		
		$this->roots = array();
		foreach ($topics as $topic){
			if ($topic->parent_key != null && array_key_exists($topic->parent_key, $topics)) {
				$topic->parent = $topics[$topic->parent_key];
			} else {
				$this->roots[] = $topic;
			}
		}
		
		$this->topics = $topics;
	}
}
